const Router = require('koa-router')
const { Statistics } = require('../database/models/statistics')
const { Metadata } = require('../database/models/metadata')
// const { sequelize } = require('../database/db')
// const { QueryTypes } = require('sequelize')
// const Op = require('sequelize').Op
// const check = require('../pem/check')

let router = new Router()

router.get('/', async(ctx) => {
    try {
        const data = await Metadata.findAll({
            attributes: ['VirusTaxonomyID'],
            group: ['VirusTaxonomyID']
        });
        await Metadata.destroy({where: {}, truncate: true})
        for (var i = 0; i < data.length; i++) {
            const arr = await Metadata.findAll({
                where: {
                    VirusTaxonomyID: data[i].VirusTaxonomyID
                }
            });
            const chartList = [
                {name: 'System', data: []}, {name: 'Organ', data: []},
                {name: 'Age Group', data: []}, {name: 'Gender', data: []},
                {name: 'Country/Regino', data: []}, {name: 'Race', data: []},
            ]
            chartList[0].data = format('System', arr)
            chartList[1].data = format('Tissue', arr)
            chartList[2].data = format('AgeGroup', arr)
            chartList[3].data = format('Gender', arr)
            chartList[4].data = format('Country', arr)
            chartList[5].data = format('Race', arr)
            await Statistics.create({ vid: data[i].VirusTaxonomyID, jsonString: JSON.stringify(chartList) })
        }
        ctx.body = {
            code: 101,
            msg: '成功'
        }
    } catch (err) {
        ctx.body = {
            code: 102,
            data: null,
            msg: ''
        }
    }
})

function format(name, data) {
    const Obj = {}
    let List = []
    data.forEach(v => {
        if (Obj[v[name]]) {
            Obj[v[name]].data[0] += 1
        } else {
            Obj[v[name]] = {
                "name": v[name],
                "type": "bar",
                "barWidth": "45%",
                "stack": '总量',
                "label": {"show": true, "position": "inside", "color": '#333', 'fontWeight': 600},
                "data": [1]
            }
        }
    })
    for(const k in Obj) {
        List.push(Obj[k])
    }
    List = List.sort((a, b) => b.data[0] - a.data[0])
    if (List.length > 5) {
        const arr1 = List.slice(0, 5)
        const arr2 = List.slice(5)
        let num = arr2.reduce((a, b) => {
            return a + b.data[0]
        }, 0)
        const other = {
            "name": 'other',
            "type": "bar",
            "barWidth": "45%",
            "stack": '总量',
            "label": {"show": true, "position": "inside", "color": '#333', 'fontWeight': 600},
            "data": [num]
        }
        return [...arr1, other]
    }
    return List
}

module.exports = router
